import { getContext } from '@/context/common/applicationContext'
import { Component } from 'react'

/**
 * 消息定时任务组件
 * @author liu_jshan
 * @version 1.0  20240502
 */
class MessageScheduledTask extends Component {

    constructor(props) {
        super(props)
        this.state = {
            taskIds: []
        }
    }

    async componentDidMount() {
        if (this.props.updateUserMessage && typeof this.props.updateUserMessage === 'function') {
            //每一分钟更新一次消息
            await this.addTask(async () => {
                await this.props.updateUserMessage()
            }, 1000 * 60)
        }
    }

    /**
     * 添加定时任务
     * @param {Function} func 任务
     * @param {Number} time 时间 ms
     */
    addTask = async (func, time) => {
        let taskId = setInterval(func, time)
        const taskIds = this.state.taskIds
        taskIds.push(taskId)
        await new Promise(resolve => {
            this.setState({ taskIds }, resolve)
        })
    }

    async componentWillUnmount() {
        //清楚定时任务
        this.state.taskIds.forEach(item => {
            clearInterval(item)
        })
    }
    render() {
        return ''
    }
}

export default getContext(MessageScheduledTask)